package com.snopy.leetcode.index1_1000.index1_100;

import java.util.Arrays;
import java.util.Comparator;

/**
 * @author snopy
 * @version 1.0.0
 * @classname Question14
 * @description 最长公共前缀
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 * 如果不存在公共前缀，返回空字符串 ""
 *
 * @email 77912204@qq.com
 * @date 2022/03/31 20:10
 */
public class Question14 {
    public static void main(String[] args) {
        String[] strs = new String[]{"a"};
        String ret = longestCommonPrefix(strs);
        System.out.println(ret);
    }
    public static String longestCommonPrefix(String[] strs) {
        if (strs==null || strs.length==0){
            return "";
        }
        if (strs.length==1){
            return strs[0];
        }
        Arrays.sort(strs,(o1,o2)->{return o1.length()-o2.length();});

        String ret = "";
        boolean flag = false;
        for (int i = 0;i<strs[0].length();i++) {

            for (int k = 1;k<strs.length;k++){
                if (strs[0].charAt(i)!=strs[k].charAt(i)){
                    return ret;
                }
            }
            ret =  strs[0].substring(0,i+1);

        }
            return ret;
    }
}
